package tools

import (
    "context"
    "fmt"
    "time"

    "github.com/go-git/go-git/v5"
    "github.com/go-git/go-git/v5/plumbing/object"
)

func GetGitSummary(ctx context.Context, repoPath string) (string, error) {
    r, err := git.PlainOpen(repoPath)
    if err != nil {
        return "", fmt.Errorf("failed to open repo: %w", err)
    }

    ref, err := r.Head()
    if err != nil {
        return "", fmt.Errorf("failed to get head: %w", err)
    }

    cIter, err := r.Log(&git.LogOptions{From: ref.Hash()})
    if err != nil {
        return "", err
    }

    var summary string
    cutoff := time.Now().AddDate(0, 0, -7)
    _ = cIter.ForEach(func(c *object.Commit) error {
        if c.Committer.When.Before(cutoff) {
            return nil
        }
        summary += fmt.Sprintf("- [%s] %s (%s)\n", c.Committer.When.Format("01-02"), c.Message, c.Author.Name)
        return nil
    })
    if summary == "" {
        summary = "本周暂无提交记录。"
    }
    return summary, nil
}
